package com.ossean.match.matchprocess;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import com.ossean.match.dao.RelativeMemoDao;
import com.ossean.match.lucene.LuceneIndex;
import com.ossean.match.model.RelativeMemo;

@Component("memotoprjmatch")
public class MemoToPrjMatch implements Runnable {
	private Logger logger = LoggerFactory.getLogger(getClass());
	private MatchIncrement matchIncrement = null;
	private int step = 2000; // setting the numbers of memos for every reading
	@Qualifier("match")
	@Autowired
	private Match match;
	@Resource
	private RelativeMemoDao memoDao;

	public void setMatchIncrement(MatchIncrement matchIncrement) {
		this.matchIncrement = matchIncrement;
	}

	/**
	 *  new memos match to all projects and adding memos index
	 * @param conn
	 * @throws SQLException
	 * @throws IOException
	 */
	public void memoToPrjIncrement() throws SQLException,
			IOException {
		matchIncrement.setCurrentMatchDone(false);
		matchIncrement.getMatchRecord();
		int startId = matchIncrement.getMemoHistory();
		int endId = startId + step;
		int lastMemoId = memoDao.getLastMemoId();
		if ((lastMemoId - endId) <= step) {
			endId = lastMemoId;
		}
		LuceneIndex luceneIndex = new LuceneIndex();
		while (startId < lastMemoId) {
			List<RelativeMemo> memos = memoDao.getMemoInfo(startId, endId);
			if (memos != null && memos.size() > 0) {
				match.memoToPrjMatch(memos);
				matchIncrement.setMemoHistory(endId);
				// adding memos index and save the record
				luceneIndex.memoIndexIncrement(memos);
			}
			logger.info("relative_memos_to_osps matched to : "
					+ matchIncrement.getMemoHistory());
			logger.info("relative_memos_to_osps remain_to_match : "
					+ (lastMemoId - endId));
			// finishing matching, writing the record to "record.txt"
			matchIncrement.writeIntoRecord();
			if ((lastMemoId - endId) <= step) {
				startId = endId;
				endId = lastMemoId;
			}
			else {
				startId = endId;
				endId += step;
			}
		}
		matchIncrement.setCurrentMatchDone(true);
	}
	public void run() {
		if (matchIncrement.isNewMemoComing()) {
			logger.info("start relative_memos_to_osps match!!!");
			try {
				memoToPrjIncrement();
			} catch (SQLException e) {
				logger.error("SQLException: " + e);
			} catch (IOException e) {
				logger.error("IOException: " + e);
			}
		}
	}
}
